const AdminBiz = require('../../../../store/admin_biz_config.js');
// 导入路径辅助模块，避免重复引用
const pathImport = require('../helpers/path_import.js');
const { pageHelper, cloudHelper, validate } = pathImport;
const PublicBiz = require('/comm/biz/public_biz.js');
const AdminNewsBiz = require('../../../../services/admin/news_service.js');
const projectSetting = require('/config/projects_config.js');
const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { contentStore } = require('../../../../store/content_store.js');

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		// 本地数据，会与store中的数据合并
		imgList: [],
		desc: '',
		cateId: '',
		cateName: '',
		forms: [],
		title: '',
		order: 0
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		if (!AdminBiz.isAdmin(this)) return;

		// 创建MobX绑定
		this.storeBindings = createStoreBindings(this, {
			store: contentStore,
			fields: ['formContent', 'isEditing'],
			actions: ['setFormContent', 'getContentFromEditor', 'setEditingStatus', 'getContentDesc']
		});

		// 确保formContent是一个有效的数组
		if (!this.formContent || !Array.isArray(this.formContent)) {
			this.setFormContent([{
				type: 'text',
				val: ''
			}]);
		}

		wx.setNavigationBarTitle({
			title: projectSetting.NEWS_NAME + '-添加',
		});

		this.setData(AdminNewsBiz.initFormData()); // 初始化表单数据
		this.setData({
			isLoad: true
		});

		this._setContentDesc();
	},

	_setContentDesc: function () {
		// 使用MobX的getContentDesc方法
		const desc = this.getContentDesc();
		this.setData({
			contentDesc: desc || '未填写'
		});
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		// 清理MobX绑定
		this.storeBindings.destroyStoreBindings();
	},

	model: function (e) {
		pageHelper.model(this, e);
	},

	/** 
	 * 数据提交
	 */
	bindFormSubmit: async function () {
		if (!AdminBiz.isAdmin(this)) return;

		let data = this.data;
		if (!this.formContent || this.formContent.length == 0) {
			return pageHelper.showModal('详细内容不能为空');
		}
		data = validate.check(data, AdminNewsBiz.CHECK_FORM, this);
		if (!data) return;

		let forms = this.selectComponent("#cmpt-form").getForms(true);
		if (!forms) return;
		data.forms = forms;

		data.cateName = AdminNewsBiz.getCateName(data.cateId);

		try {
			if (this.data.imgList.length == 0) {
				return pageHelper.showModal('请上传封面图');
			}

			// 提取简介
			data.desc = PublicBiz.getRichEditorDesc(data.desc, this.formContent);

			// 先创建，再上传 
			let result = await cloudHelper.callCloudSumbit('admin/news_insert', data);
			let newsId = result.data.id;

			// 封面图片 提交处理 
			wx.showLoading({
				title: '提交中...',
				mask: true
			});
			await cloudHelper.transCoverTempPics(this.data.imgList, 'news/', newsId, 'admin/news_update_pic');

			// 富文本
			if (this.formContent && this.formContent.length > 0) {
				wx.showLoading({
					title: '提交中...',
					mask: true
				});
				let content = await cloudHelper.transRichEditorTempPics(this.formContent, 'news/', newsId, 'admin/news_update_content');
				this.setFormContent(content);
			}

			await cloudHelper.transFormsTempPics(forms, 'news/', newsId, 'admin/news_update_forms');

			let callback = async function () {
				PublicBiz.removeCacheList('admin-news-list');
				PublicBiz.removeCacheList('news-list');
				wx.navigateBack();
			}
			pageHelper.showSuccToast('添加成功', 2000, callback);

		} catch (err) {
			console.log(err);
		}
	},

	bindImgUploadCmpt: function (e) {
		this.setData({
			imgList: e.detail
		});
	},

	url: function (e) {
		pageHelper.url(e, this);
	}
})